<template>
  <view class="device-goods-list">
    <BaseNavbar :title="title" />
    <view class="top-bg" v-if="isFromDevice || isFromReplenish"
      :style="{ height: isFromReplenish ? '420rpx' : '435rpx' }">
      <!-- <image class="bg-img" :src="bgImg" /> -->
      <image class="bg-img" src="@/pagesB/static/img/icon/topbag.jpg" />
      <view class="bg-content flexColumnBetween">
        <view class="title">{{
          umDetail.hotelName || "暂无" + vPointName + "昵称"
        }}</view>
        <view class="flexRowBetween">{{
          umDetail.addressDetail || "暂无具体位置"
        }}</view>
        <view class="flexRowBetween">
          <view>设备编号：{{ device_sn }}</view>
          <view v-if="isFromReplenish">
            <view class="bind">
              <block v-if="umDetail.hotelId > 0">
                <image class="bind_icon" src="@/pagesB/static/img/icon/isBind_icon.png" />
                <view class="theme-color">已绑定</view>
              </block>
              <block v-else>
                <image class="bind_icon" src="@/pagesB/static/img/icon/noBind_icon.png" />
                <view class="text-warn">未绑定</view>
              </block>
            </view>
          </view>
        </view>
        <!-- <view class="flexRowBetween" v-if="isGameDevice">
          <view slot="">
            剩余水量：{{ umDetail.remain_game_time>0?(umDetail.remain_game_time/vGamingTime).toFixed(1):0  }}升</view
          >
        </view> -->

        <view class="flexRowBetween" v-if="isFromDevice">
          <view>拥有者：{{ umDetail.user_login || "" }}</view>
          <view class="online">
            <block v-if="umDetail.status == 1">
              <image class="online_icon" src="@/pagesB/static/img/icon/device_online_icon.png" />
              <view class="theme-color">在线</view>
            </block>
            <block v-if="umDetail.status == 2">
              <image class="online_icon" src="@/pagesB/static/img/icon/device_unline_icon.png" />
              <view class="text-warn">异常</view>
            </block>
            <block v-if="umDetail.status == 3">
              <image class="online_icon" src="@/pagesB/static/img/icon/device_unline_icon.png" />
              <view class="text-warn">离线</view>
            </block>
          </view>
        </view>

        <view v-if="isFromReplenish">
          <view class="goods_status" v-if="isBleDevice" @click.stop="initLinkBle">
            <view class="goods_status_title">蓝牙连接状态：</view>
            <view>{{ bBleConnected ? "已连接" : "未连接(点我重新连接)" }}</view>
          </view>
          <view class="goods_status" v-else>
            <block v-if="isGameDevice == false">
              <view class="goods_status_title">商品状态：</view>
              <view>{{ stockData }}</view>
            </block>
          </view>
        </view>
        <view class="flextRowPostion">
          <view class="flexRowwiter" v-if="isGameDevice">
            <view>
              <image class="waterbag" src="@/pagesB/static/img/icon/waterbag.png">

              </image>
            </view>
            <view class="watertext">
              <view>
                <text>{{ umDetail.remain_game_time > 0 ? (umDetail.remain_game_time / vGamingTime).toFixed(1) : 0
                }}</text>
                <text>L</text>
              </view>
              <view>剩余水量 (升)</view>
            </view>
          </view>
          <view class="flexRowwiter" v-if="isGameDevice">
            <view>
              <image class="waterbag" src="@/pagesB/static/img/icon/timebag.png">

              </image>
            </view>
            <view class="watertext">
              <view>
                <text>{{ umDetail.remain_game_time > 0 ? umDetail.remain_game_time.toFixed(0) : 0 }}</text>
                <text>min</text>
              </view>
              <view>可玩时间 (分钟)</view>
            </view>
          </view>
          <view class="flexRowbtn" @click="water" v-if="isGameDevice && isFromReplenish">
            <image src="@/pagesB/static/img/icon/textbag.png" alt=""></image>
            <view>
              补充泡泡液
            </view>
          </view>
        </view>


        <view class="flexRowBtext" v-if="isGameDevice">
          <view slot="">
            1升泡泡液对应时长：{{ vGamingTime || "0" }}分钟</view>
        </view>

      </view>
    </view>
    <ComList :loading-type="loadingType">
      <DeviceGoodsListCard :from="fromData" v-for="(item, index) in listData" :key="item.id" :info="item"
        :index="index + 1" @del="del(item, index)" @edit="edit" @open="openDoor(index + 1)" @supply="supply(index)"
        @start="start(index)" @stop="stop(index)" />
    </ComList>

    <BaseModal :show.sync="isShowSupplyModal" @confirm="confirmSupply">
      <view slot="default">
        <BaseInput v-model="supplyNum" placeholder="请输入补货量" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowWaterModal" @confirm="confirmWater">
      <view slot=""> 可玩时间：{{ tiem }}</view>
      <view slot="default">
        <input class="isReplenish" v-model="WarterNum" placeholder="请输入补货水量(0.0-3.0)升" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowStartModal" @confirm="confirmStart">
      <view slot="default">
        <BaseInput v-model="length_time" :disabled="vInputDisable" placeholder="请输入启动时长(分钟)" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowDelModal" content="您的商品将会删除，是否继续删除？" @confirm="confirmDel" />
    <BaseModal :show.sync="isShowMickModal" @confirm="confirmMick">
      <view slot="default">
        <BaseRadio :list="mickList" :radioIndex.sync="selectMickRadio" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowLightModal" @confirm="confirmLight">
      <view slot="default">
        <BaseRadio :list="ligthList" :radioIndex.sync="selectLightRadio" />
      </view>
    </BaseModal>
    <BaseModal :show.sync="isShowVolumeModal" @confirm="confirmVolume">
      <view slot="default">
        <!-- 调节音量 -->
        <view class="wrap">
          <slider :value="constraintLength" @change="sliderChange" min="0" max="100" step="1" activeColor="#FFCC33"
            backgroundColor="#000000" block-color="#8A6DE9" block-size="20" />
          <view style="margin-top: 15px; font-size: 15px">音量值:{{ constraintLength }}</view>
        </view>
      </view>
    </BaseModal>
    <!-- 控制音乐时长 -->
    <BaseModal :show.sync="isShowMusicModal" @confirm="confirmMusicLength">
      <view slot="default">
        <!-- 调节音量 -->
        <view style="display: felx">
          <uni-input placeholder="请输入播放时长(分钟)" ref="watchTime"></uni-input>
        </view>
      </view>
    </BaseModal>
    <!-- 出泡泡提示 -->
    <BaseModal :show.sync="isShowStartMain" @confirm="comfirmStartMain">
      <TextLength :num="length_time"></TextLength>
    </BaseModal>
    <view class="preserve" :style="{ paddingBottom: 20 + vIphoneXBottomHeight + 'rpx' }">
      <!-- <view v-if="isFromDevice">
        <BaseButton type="primary">保 存</BaseButton>
      </view> -->
      <view v-if="isFromPlace" class="flexRowBetween">
        <BaseButton type="default" width="330" @onClick="saveAndApply(false)">
          保 存
        </BaseButton>
        <BaseButton type="primary" width="330" @onClick="saveAndApply(true)">
          保存并应用到设备
        </BaseButton>
      </view>
      <view v-if="isFromReplenish" class="flexRowBetween">
        <block v-if="isRechargeDevice">
          <BaseButton type="primary" width="300" @onClick="doRecharge(1)">
            充电(1分钟)
          </BaseButton>
          <BaseButton type="default" width="300" @onClick="doRecharge(0)">
            结束充电
          </BaseButton>
        </block>
        <block v-else>
          <block v-if="isGameDevice">
            <block v-if="vUserInfo.role_id != 6 && vUserInfo.role_id != 7">
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="start(0)">
                启动
              </BaseButton>
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="start(1)">
                出泡泡
              </BaseButton>
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="adjustVolume()"
                v-if="umDetail.isTurnVolume">
                调节音量
              </BaseButton>
              <BaseButton type="primary" style="width: 30%; margin: 5rpx" @onClick="stop(-1)">
                停止
              </BaseButton>
              <!-- <BaseButton type="primary" style="width: 30%; margin: 5rpx" @onClick="clear(5, 0)">
                重置
              </BaseButton> -->
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="openMick()">
                提示音
              </BaseButton>
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="openLight()">
                控制灯
              </BaseButton>
              <BaseButton type="primary" style="width: 30%; margin: 5rpx; display: none" @onClick="openLight()">
                控制灯
              </BaseButton>
              <BaseButton type="default" style="width: 30%; margin: 5rpx" @onClick="openMusic()">
                开启音乐
              </BaseButton>
            </block>
            <block v-else>
              <BaseButton type="default" style="width: 50%; margin: 5rpx" @onClick="startGameDevice(2, 1)">
                开启泡泡+音乐60秒
              </BaseButton>
              <BaseButton type="default" style="width: 40%; margin: 5rpx" @onClick="startMusic(1)">
                开启音乐60秒
              </BaseButton>
              <BaseButton type="default" style="width: 40%; margin: 5rpx" @onClick="stop(-1)">
                停止
              </BaseButton>
            </block>
          </block>
          <block v-else>
            <BaseButton type="default" width="210" @onClick="goReplenishRecord">
              日志
            </BaseButton>
            <BaseButton type="default" width="210" @onClick="openAll">
              一键出货
            </BaseButton>
            <BaseButton type="primary" width="210" @onClick="repAll">
              一键补货
            </BaseButton>
          </block>
        </block>
      </view>
    </view>
    <SafeBlock :height="120" />
  </view>
</template>

<script>
import BaseNavbar from "@/components/base/BaseNavbar.vue";
import DeviceGoodsListCard from "../components/cards/DeviceGoodsListCard.vue";
import BaseButton from "@/components/base/BaseButton.vue";
import BaseModal from "@/components/base/BaseModal.vue";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseRadio from "@/components/base/BaseRadio.vue";
import myPull from "@/mixins/myPull.js";
import ComList from "@/components/list/ComList.vue";
import ble from "@/wxutil/ble.js";
import { bleMixin } from "@/mixins/bleMixin";
import SafeBlock from "@/components/common/SafeBlock.vue";
import UniSlider from "../../components/uni-slider/UniSlider.vue";
import UniInput from "../../components/uni-slider/UniInput.vue";
import USlider from "uview-ui/components/u-slider/u-slider.vue";
import TextLength from '@/components/text/TextLength.vue'
export default {
  components: {
    BaseNavbar,
    DeviceGoodsListCard,
    BaseButton,
    BaseModal,
    BaseInput,
    BaseRadio,
    ComList,
    SafeBlock,
    UniSlider,
    UniInput,
    USlider,
    TextLength
  },
  data() {
    return {
      title: "设备商品",
      fromData: "",
      isFromDevice: false,
      isFromPlace: false,
      isFromReplenish: false,
      isFromIndexScan: false,
      isShowSupplyModal: false,
      isShowWaterModal: false, //补水
      WarterNum: "", //水量
      supplyNum: "",
      device_sn: "",
      mid: "",
      pageSize: 21,
      umDetail: {},
      hotel_id: "", //点位id
      selectIndex: 0, //选中数据项
      isBleDevice: false, // 是否是蓝牙设备
      isRechargeDevice: false, //是否是充电设备
      isGameDevice: false, // 是否是游戏设备
      isTurnVolume: false, // 是否能调节音量
      isShowStartMain: false,//出泡泡超过三分提示
      bBleConnected: false, //蓝牙设备是否连接
      openChannelList: [], //当前需要打开的仓门channel列表
      bNeedReplenish: false, //是否需要补货

      number: 0, //格子数
      stockData: "暂无", //库存信息
      isShowDelModal: false, //是否显示 是否删除商品弹框
      selecDelGoodsInfo: {}, //选择删除商品的信息
      isShowStartModal: false, // 是否显示启动时间
      isShowLightModal: false, // 是否关灯
      isShowMickModal:false,
      length_time: 1, // 启动时长
      selectLightRadio: 1,
      selectMickRadio:1,
      constraintLength: 100, //音量大小
      adjust_time: 1, //音乐时长
      waterSum: "", //剩余水量
      ligthList: [
        {
          title: "关灯",
          name: 1,
          selectIndex: 0,
        },
        {
          title: "开灯",
          name: 2,
          selectIndex: 1,
        },
      ],
      mickList: [
        {
          title: "关闭",
          name: 1,
          selectIndex: 0,
        },
        {
          title: "开启",
          name: 2,
          selectIndex: 1,
        },
      ],
      isShowVolumeModal: false, //是否显示调节音量
      isShowMusicModal: false, //是否显示输入音乐时长,
      isReplenish: false, //是否是补货页面来的
    };
  },
  computed: {
    bgImg() {
      if (this.isFromReplenish)
        return require("@/pagesB/static/img/icon/topbag.jpg");
      return require("@/pagesB/static/img/deviceGoodsBg1.png");
    },
    has2GStatus() {
      return !this.isBleDevice;
    },
  },
  methods: {
    /* 补充水量 */
    checkNumber(item) {
      // this.WarterNum = item > 3 ? 3 : item < 0 ? 0 : item;
      // console.log(this.WarterNum, item, item * 1 > 3 || item * 1 < 0);
      if (item > 3) {
        this.isShowErr("最大为3升自动修改为3升");
        this.WarterNum = 3.0;
        // return
      } else if (item < 0) {
        this.isShowErr("最小为0升自动修改为0升");
        this.WarterNum = 0.0;
        // return

      } else if (!item) {
        this.WarterNum = 0.0;
        // return

      } else if (this.WarterNum.toString().split('.').pop().length > 1) {
        this.WarterNum = Math.floor(item * 10) / 10;
        this.isShowErr("最多一位小数自动修改为" + this.WarterNum);
        // return
      }
      // this.WarterNum = this.WarterNum.replace(/[1-3]/g,'')
    },
    // 滑动事件触发值
    sliderChange(e) {
      this.constraintLength = e.detail.value;
    },
    tage(e) {
      console.log(e);
    },
    initLinkBle() {
      if (!this.bBleConnected) {
        this.startBleConnect(
          this.umDetail.device_sn,
          this.umDetail.deviceType,
          this.umDetail.mkey
        ); // 初始化蓝牙设备
        return false;
      }
      return true;
    },
    //测试充电
    doRecharge(time = 1) {
      if (!this.bBleConnected) {
        this.startBleConnect(
          this.umDetail.device_sn,
          this.umDetail.deviceType,
          this.umDetail.mkey
        ); // 初始化蓝牙设备
        return;
      }
      ble.rechargeDevice(time, (isOk = true) => {
        this.isShowSuccess("写入指令完成");
      });
    },
    //执行开门
    openDoor(doors) {
      if (this.has2GStatus) {
        //2g主板开门
        let data = {
          device_sn: this.device_sn,
          doors,
        };
        this.$u.api.openDoor(data).then((res) => {
          this.isShowSuccess("操作成功");
        });
      } else {
        if (this.isNumber(doors)) {
          this.openBleDoor(doors);
        } else {
          this.openBleAllDoor(doors);
        }
      }
    },
    // 一键开门
    openAll() {
      let doors = 1;
      for (let i = 2; i <= this.number; i++) {
        doors = doors + "," + i;
      }
      this.openDoor(doors);
    },
    // 打开蓝牙连接的门
    openBleDoor: function (channel) {
      if (!this.bBleConnected) {
        this.startBleConnect(
          this.umDetail.device_sn,
          this.umDetail.deviceType,
          this.umDetail.mkey
        ); // 初始化蓝牙设备
        return;
      }
      console.log("---> 蓝牙开门", channel);
      ble.openVendingLock(this.btOpenCallback, channel);
    },
    //打开蓝牙设备的全部门
    openBleAllDoor: function (doors) {
      if (!this.bBleConnected) {
        this.startBleConnect(
          this.umDetail.device_sn,
          this.umDetail.deviceType,
          this.umDetail.mkey
        ); // 初始化蓝牙设备
        return;
      }
      ble.openAllLock(this.btOpenCallback);
    },
    //开门回调
    btOpenCallback(isOpen, types, currentSerialVal, currentOrderSN) {
      // 开锁回调
      if (isOpen) {
        // 开门成功
        uni.showToast({
          title: "开锁成功",
          icon: "success",
        });
        //判断是否需要继续打开其他锁
        this.openChannelList.splice(0, 1);
        if (this.openChannelList.length) {
          this.openDoor(this.openChannelList[0]);
        } else {
          //判断是否需要调用补货接口
          if (this.bNeedReplenish) {
            this.bNeedReplenish = false;
            this.repAllRequest();
          }
        }
      } else {
        // 开门失败
        uni.showToast({
          title: "开锁失败",
          icon: "error",
        });
      }
    },
    //一键补货
    repAll() {
      if (this.isBleDevice) {
        if (!this.bBleConnected) {
          this.startBleConnect(
            this.umDetail.device_sn,
            this.umDetail.deviceType,
            this.umDetail.mkey
          ); // 初始化蓝牙设备
          return;
        }
        //如果是蓝牙设备，则需要先打开缺货的仓门
        console.log("点击了一键补货，listData=", this.listData);
        this.listData.forEach((item, index) => {
          if (item.amount == 0) {
            this.openChannelList.push(index + 1);
          }
        });

        console.log("一键补货，需要打开的仓门列表：", this.openChannelList);
        if (this.openChannelList.length) {
          //先打开第一个仓门，然后在成功回调中继续打开仓门
          this.bNeedReplenish = true;
          this.openDoor(this.openChannelList[0]);
        }
      } else {
        this.repAllRequest();
      }
    },
    //调用补货api】
    repAllRequest() {
      let data = {
        device_sn: this.device_sn,
      };
      this.$u.api.setUMAllStock(data).then((res) => {
        this.isShowSuccess("一键补货成功~", 0, () => this.refresh(), true);
      });
    },
    //删除商品 显示modal
    del(item, index) {
      if (this.isFromPlace) {
        this.listData.splice(index, 1, { num: index + 1 });
      } else {
        this.selecDelGoodsInfo = this.listData[index];
        if (!this.selecDelGoodsInfo?.goods_id) {
          this.isShowErr("没有商品或" + this.vCargoLanes, 0);
          this.selecDelGoodsInfo = "";
          return;
        }
        // this.selecDelGoodsInfo = item;
        this.isShowDelModal = true;
      }
    },
    confirmDel() {
      let data = { device_sn: this.device_sn, num: this.selecDelGoodsInfo.num };
      this.$u.api.delDeviceGoods(data).then((res) => {
        this.isShowSuccess("删除成功", 0, this.refresh());
      });
    },

    //跳转设备商品详情
    edit(item) {
      let {
        goods_name,
        good_price,
        original_img,
        goods_id,
        default_stock,
        unit,
        free_lenth,
        pay_lenth,
        game_time,
      } = item;
      let goodsInfo = JSON.stringify({
        goods_name,
        good_price,
        original_img,
        default_stock,
        goods_id,
        unit,
        free_lenth,
        pay_lenth,
        game_time,
      });
      console.log("传递的参数", goodsInfo);
      uni.navigateTo({
        url: `/pagesB/device/DeviceGoodsEdit?${this.isFromPlace ? "from=template_place&" : ""
          }goodsInfo=${goodsInfo}&num=${item.num}&device_sn=${this.device_sn || ""
          }`,
      });
    },
    isNumber(val) {
      console.log("isNumber >  1 ");
      var regPos = /^\d+(\.\d+)?$/; //非负浮点数
      var regNeg =
        /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
      if (regPos.test(val) || regNeg.test(val)) {
        return true;
      } else {
        return false;
      }
    },
    //显示补货弹窗
    supply(i) {
      this.supplyNum = "";
      this.isShowSupplyModal = true;
      this.selectIndex = i;
    },
    //确认补货设置
    confirmSupply() {
      let data = {
        device_sn: this.device_sn,
        goods_id: this.listData[this.selectIndex]["goods_id"],
        num: this.selectIndex + 1,
        amount: this.supplyNum,
      };
      this.$u.api.setUMStock(data).then((res) => {
        this.isShowSuccess("库存设置成功", 0, () => this.refresh());
      });
    },
    // 声音大小
    adjustVolume() {
      if (this.isFromReplenish) {
        // 补货管理才能有启动
        this.isShowVolumeModal = true;
      }
    },
    // 控制音量
    confirmVolume() {
      let data = {
        device_sn: this.device_sn,
        volume: this.constraintLength * 0.3,
      };
      this.$u.api.getUserVideo(data).then((res) => {
        this.isShowSuccess(res.msg);
      });
    },
    // 播放音乐时长
    openMusic() {
      if (this.isFromReplenish) {
        this.isShowMusicModal = true;
      }
    },
    // 播放音乐时长
    confirmMusicLength() {
      this.startMusic(this.$refs.watchTime.adjust_time);
    },
    // 播放音乐
    startMusic(time) {
      let data = {
        device_sn: this.device_sn,
        length_time: time, //获取子组件传来的数据
      };
      this.$u.api.startMusic(data).then((res) => {
        console.log(res);
        this.isShowSuccess(res.msg);
      });
    },
    openMick(){
     this.isShowMickModal=true 
    },
    confirmMick(){
      let data={
        device_sn:this.device_sn,
        status:this.mickList[this.selectMickRadio - 1].selectIndex,
      };
      console.log('提交的信息',data)
      this.$u.api.turnTipMusic(data).then((res) => {
        console.log("启动设备结果4 ：", res);
        this.isShowTwo("操作成功", 1);
      });
    },
    // 控制灯
    openLight() {
      if (this.isFromReplenish) {
        // 补货管理才能有启动
        this.isShowLightModal = true;
      }
    },
    confirmLight() {
      // 控制灯
      let data = {
        device_sn: this.device_sn,
        status: this.ligthList[this.selectLightRadio - 1].selectIndex,
      };
      console.log("启动设备结果参数 3 ：", data);
      this.$u.api.turnLight(data).then((res) => {
        console.log("启动设备结果4 ：", res);
        this.isShowTwo("操作成功", 1);
      });
    },
    // 游戏设备，启动游戏设备
    start(i) {
      if (this.isFromReplenish) {
        // 补货管理才能有启动
        this.selectIndex = i;
        this.isShowStartModal = true;
      }
      console.log("启动设备结果参数 1 ：", i);
    },
  
    confirmStart() {
      // 开启游戏设备
      // this.isShowProgress = true
      if (this.length_time >= 3) {
        this.isShowStartMain = true
      } else {

        this.startGameDevice(this.selectIndex + 1, this.length_time);
      }
    },
    comfirmStartMain() {
      this.startGameDevice(this.selectIndex + 1, this.length_time);
    },
    startGameDevice(channel, time) {
      // 启动设备
      // 启动设备
      console.log("启动设备结果参数 2 ：", data);
      let data = {
        device_sn: this.device_sn,
        channel: channel, // 货道
        length_time: time,
      };
      console.log("启动设备结果参数 3 ：", data);
      this.$u.api.startUM(data).then((res) => {
        console.log("启动设备结果4 ：", res);
        this.isShowTwo("操作成功", 1);
      });
    },
    stop(i) {
      // 停止游戏设备
      if (this.isFromReplenish) {
        // 补货管理才能有启动
        this.selectIndex = i;
        this.length_time = 0;
        this.confirmStart();
      }
    },
    clear(model, status) {
      // 清除设备在使用的状态
      let data = {
        device_sn: this.device_sn,
        model: model, // 5,游戏模式 3，充电模式
        status: status, // 1.正在进行 2.未开始
      };
      let that = this;
      this.$u.api.clearUMModelStatus(data).then((res) => {
        this.isShowTwo("操作成功", 1);
      })
        .catch(err => {
          console.log('操做失败', err)
        })
        ;
    },
    getList(page, done) {
      let data = {},
        rtnData = null;
      if (this.isFromDevice || this.isFromReplenish || this.isFromIndexScan) {
        data = {
          device_sn: this.device_sn,
          limit: this.pageSize,
          mid: this.mid,
          page,
        };
        rtnData = this.$u.api.getUMShops(data);
      } else if (this.isFromPlace) {
        data = {
          hotel_id: this.hotel_id,
          page: page,
          limit: this.pageSize,
        };
        rtnData = this.$u.api.getHotelTemplate(data);
      }
      if (rtnData) {
        rtnData.then((res) => {
          if (res.umDetail) this.umDetail = res.umDetail || {};
          if (res.number) this.number = res.number || 0;
          let dataList = res.data || [];
          console.log(`获取的${this.vCargoLanes}信息：`, dataList);
          if (this.isFromPlace) {
            let newDataList = [];
            for (let i = 1; i <= 10; i++) {
              let isExist = false;

              dataList.forEach((item) => {
                if (item.num == i) {
                  newDataList.push(item);
                  isExist = true;
                }
              });
              if (!isExist) {
                newDataList.push({ num: i });
              }
            }
            dataList = newDataList;
          } else if (this.isFromDevice) {
            let temp = res.number;
            let newDataList = [];
            let nowListIndex = 0;
            for (let i = 1; i <= temp; i++) {
              if (dataList[nowListIndex]?.num == i) {
                newDataList.push(dataList[nowListIndex]);
                nowListIndex++;
              } else {
                newDataList.push({ num: i });
              }
            }
            console.log(`获取的${this.vCargoLanes}变化的数据：`, newDataList);
            dataList = newDataList;
          }
          done(dataList);
          if (this.umDetail) {
            if (ble.isBlueDevice(this.umDetail.deviceType)) {
              this.isBleDevice = true;
              if (!this.bBleConnected) {
                this.startBleConnect(
                  this.umDetail.device_sn,
                  this.umDetail.deviceType,
                  this.umDetail.mkey
                ); // 初始化蓝牙设备
              }
            }
            this.isRechargeDevice = ble.isRechargeDevice(
              this.umDetail.deviceType
            );
            this.isGameDevice = this.umDetail.isGameDevice
              ? this.umDetail.isGameDevice
              : false;
            this.isTurnVolume = this.umDetail.isTurnVolume
              ? this.umDetail.isTurnVolume
              : false;
            console.log(
              "设备是否是游戏设备：",
              this.isGameDevice,
              this.isTurnVolume
            );
            this.device_sn = this.umDetail.device_sn;
          }

          this.countStock();
        });
      }
    },
    //计算所有货道库存
    countStock() {
      let stockList = [];
      stockList = this.listData.map((item, i) => {
        if (item.unit != 3) {
          console.log('库存信息3', stockList)
          return (
            (String(i + 1).length > 1 ? i + 1 : "0" + (i + 1)) +
            `${this.vCargoLanes}库存余` +
            (item.stock || 0) +
            "件"
          );

        } else {
          console.log('库存信息2', stockList)
          return "";
        }
      });
      console.log('库存信息', stockList)
      this.stockData = stockList.join("；");
    },
    //点位来的，保存模板
    saveAndApply(type) {
      let newList = [];
      this.listData.forEach((item) => {
        console.log("id : ", item.goods_id);
        if (item.goods_id)
          newList.push({
            h_amount: 1,
            h_default_stock: item.default_stock,
            h_good_price: item.good_price,
            h_goodid: item.goods_id,
            h_num: item.num,
            unit: item.unit,
            free_lenth: item.free_lenth,
            pay_lenth: item.pay_lenth,
            game_time: item.game_time,
            name: item.goods_name,
          });
      });
      if (newList.length == 0) return this.isShowErr("请先设置模板~");
      let data = {
        h_hotelid: this.hotel_id,
        items: newList,
      };
      if (type) {
        //保存并应用到设备
        this.$u.api.saveAndApplyHotelTemplate(data).then((res) => {
          this.isShowSuccess("保存并应用成功", 1);
        });
      } else {
        //保存
        this.$u.api.saveHotelTemplate(data).then((res) => {
          this.isShowSuccess("保存成功", 1);
        });
      }
    },
    goReplenishRecord() {
      uni.navigateTo({
        url: "/pagesB/replenish/ReplenishRecord?device_sn=" + this.device_sn,
      });
    },
    /* 补水 */
    /* 确认方法和事件哪里的问题 */
    water() {
      console.log(1)
      this.isShowWaterModal = true;
      if (this.WarterNum > 0) {
        this.WarterNum = (this.umDetail.remain_game_time / this.vGamingTime).toFixed(1);
      } else {
        this.WarterNum = 0.0
      }
    },
    /* 确认补水 */
    confirmWater() {
      this.checkNumber(this.WarterNum)
      let data = {
        device_sn: this.device_sn,
        cbm: this.WarterNum,
      };
      console.log("水数据", data);
      this.$u.api
        .setUMAllStock(data)
        .then((res) => {
          console.log("补水返回结果", res);
          this.isShowTwo("更改成功", 1);
          this.refresh();
        })
        .catch((error) => {
          this.isShowErr("更改失败");
          console.log("错误补水返回结果", error);
        });
    },
  },
  computed: {
    tiem() {
      console.log('是否是字符串', this.WarterNum)
      if (!this.WarterNum || this.WarterNum < 0) {
        return 0
      }
      return this.WarterNum * this.vGamingTime;
    },
    tiem1() {
      return this.umDetail.remain_game_time;
    },
  },
  onLoad(opt) {
    console.log("🚀 ~ opt", opt);

    if (opt?.from) {
      this.fromData = opt.from;
      if (this.fromData == "device") {
        //设备来的
        this.title = "设备商品";
        this.isFromDevice = true;
        this.device_sn = opt.device_sn;
      } else if (this.fromData == "place") {
        //点位来的
        this.title = `${this.vCargoLanes}模板`;
        this.isFromPlace = true;
        this.hotel_id = opt.id;
      } else if (this.fromData == "replenish") {
        //补货来的
        this.title = "设备操作";
        this.isFromReplenish = true;
        this.device_sn = opt.device_sn;
      } else if (this.fromData == "index_scan") {
        //首页扫码来的
        if (opt.isFrom == "replenish") {
          this.title = "设备操作";
          this.isFromReplenish = true;
          this.isReplenish = true;
        } else if (opt.isFrom == "device_goods") {
          this.title = "设备商品";
          this.isFromDevice = true;
        }
        this.isFromIndexScan = true;
        this.mid = opt.mid;
        console.log("🚀 ~  this.mid", this.mid);
      }
    }
    if(this.vInputDisable){
      this.length_time=this.vTime
    }
    this.refresh();
    this.isBleDevice = getApp().globalData.connected;
    //监听蓝牙连接成功事件
    uni.$on("event_ble_connect_changed", (e) => {
      console.log("🚀 ~ 收到蓝牙状态改变事件", e);
      this.bBleConnected = e.connected;
      getApp().globalData.connected = e.connected;
    });
  },
  onShow(e) {
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1]; // 当前页
    if (currPage.data.isDoRefresh == true) {
      // 是否刷新
      currPage.data.isDoRefresh = false;
      this.goodsName = "";
      this.refresh();
    }
    if (currPage.data.item) {
      let currItem = currPage.data.item;
      this.listData.splice(currItem.num - 1, 1, currItem);
    }
  },

  onUnload() {
    if (this.isBleDevice) {
      console.log("直接关闭蓝牙,ble=", ble);
      uni.hideLoading();
      ble.closeBLEConnection();
    }
  },
  mixins: [myPull(), bleMixin],
};
</script>

<style lang="scss">
page {
  background-color: $pageBgColor;
}
</style>
<style lang="scss" scoped>
.wrap {
  padding: 30rpx;
}

.top-bg {

  position: relative;
  height: 328rpx;
  background-color: $themeColor;

  .bg-img {
    width: 100%;
    height: 100%;
  }

  .textMaxTwoLine {
    font-size: 15rpx;
  }

  .bg-content {
    width: 100%;
    // height: 100%;

    position: absolute;
    top: 0;
    left: 0;
    color: $textWhite;
    font-size: $font-size-base;
    box-sizing: border-box;
    padding: 35rpx 30rpx;

    .title {
      font-weight: bold;
      font-size: $font-size-middle;
    }

    .goods_status {
      width: 100%;
      display: flex;

      &_title {
        white-space: nowrap;
      }
    }
  }
}

.isReplenish {
  margin: 10rpx 0;
  border: 1rpx solid #f7f7f7;
}

.preserve {
  width: 100%;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  background-color: $uni-bg-color;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999999;

  .flexRowBetween {
    width: 100%;
    flex-wrap: wrap;
  }
}

.flexRowBtext {
  font-size: 24rpx;
  color: #74b5ff;
  text-decoration: underline;
}

.flexRowwiter {
  position: relative;
  display: inline-block;
  width: 165rpx;
  height: 190rpx;
  margin-right: 40rpx;
  border-radius: 15rpx;

  // border: 1px solid #000;
  overflow: hidden;

  image {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }

  .watertext {

    width: 100%;
    height: 190rpx;
    display: flex;
    // border: 1px solid #000;
    position: absolute;
    display: flex;
    flex-direction: column;
    text-align: center;
    justify-content: center;

    >view {
      width: 100%;
      // margin: auto;
      // border: 1px solid #000;
    }

    view:nth-child(1) {
      font-weight: bold;
      margin-top: 50rpx;
      margin-right: 10rpx;
    }

    view text:nth-child(1) {
      // border: 1px solid #000;
      display: inline-block;
      margin-right: 10rpx;
      font-size: 45rpx;
    }

    view text:nth-child(2) {
      // border: 1px solid #000;
      display: inline-block;
      font-size: 20rpx;
    }

    view:nth-child(2) {
      display: inline-block;
      margin-top: 20rpx;
      font-size: 19rpx;
    }

    // align-items: center;
    // justify-content: center;
  }

  // width: 100%;
  // height: 100%;
}

.flextRowPostion {
  margin: 10rpx 0;
  display: flex;
  align-items: baseline;

  >view {
    vertical-align: bottom;
    // border: 1px solid #000;
    display: inline-block;

  }
}

.flexRowbtn {
  margin-left: 40rpx;
  position: relative;
  // border: 1px solid #000;
  width: 250rpx;
  height: 90rpx;

  image {
    left: 0;
    top: 0;
    position: absolute;
    width: 100%;
    height: 100%;
  }

  >view {
    font-size: 35rpx;
    font-weight: bold;
    left: 0;
    top: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    // border: 1px solid #000;
  }
}

// ::v-deep{
//   u-slider{
//     width: 100px;
//     overflow: hidden;
//   }</style>
